#include "includes.h"
#include "xrj_protocol.h"
#include "includes.h"
#include <string.h> 
#include <stdio.h>  
#include <stdbool.h>
#include <IOdevice.h>
#include "MIIC2.h"
#include "lm75a.h"

#define		LM75A_ADDR		0X90   //i2c slave address
#define		REG_TEMP		0X00		
#define		REG_CONF		0X01		
#define		REG_THYST		0X02		
#define		REG_TOS			0X03	


INT32 I2C_ReadReg(UINT8 DevAddr, UINT8 RegAddr,UINT8 *read_buff,INT32 read_size)
{
INT32 i;
	MIIC2_Start();
	MIIC2_Write_Byte(DevAddr);
	if (MIIC2_WaitAck() == FALSE)
	{
		return -1;
	}	
	MIIC2_Write_Byte(RegAddr);
	if (MIIC2_WaitAck() == FALSE)
	{
		return -1;
	}	
	MIIC2_Start();
	MIIC2_Write_Byte(DevAddr|0x01);
	if (MIIC2_WaitAck() == FALSE)
	{
		return -1;
	}	
	for (i = 0;i<(read_size-1);i++)
	{
		read_buff[i] = MIIC2_Read_Byte();	
		MIIC2_Ack();	
	}	
	read_buff[read_size-1] = MIIC2_Read_Byte();
	MIIC2_NoAck();
	MIIC2_Stop();
	return 0;
}



INT32 LM75A_Read_Temperature(INT32 *tem)
{	
INT32 ret;	
INT32 Temp; 
UINT8 TestBuf[10];	
	ret = I2C_ReadReg(LM75A_ADDR, 0x00, TestBuf, 0x02);
	
	if (ret == 0)
	{
		Temp = TestBuf[0]&0x7f;
		if (TestBuf[0]&0x80)
		{
			Temp = (-Temp);	
		}	
		*tem = Temp; 
		
		/*
		Temp1 = TestBuf[0];
		Temp1 >>= 5;
		Temp2 = TestBuf[1]&0x7f;
		Temp2 <<= 3;
		Temp2 |= Temp1;
		tem = Temp1;
		if (TestBuf[0]&0x80)
		{
			
		}
		else
		{
		
		}	*/
	}	
	return ret;
}


INT32 Tempearture_buf;
INT32 LM75A_Init(void)
{	
	MIIC2_Init();
	return 0;
}	


INT32 Cnt_Loop;
void LM75A_PROC(void)
{
INT32 buf;	
	Cnt_Loop++;
	if (Cnt_Loop > 200)
	{
		Cnt_Loop++;	
		if (LM75A_Read_Temperature(&buf) == 0)
		{
			XRJ_mutex_lock(&Device_Value.Lock);
			Device_Value.TEMPERATURE_Report = buf;
			XRJ_mutex_unlock(&Device_Value.Lock);	
		//	Send_Report_Message(IOT__UNIT_INDEX__TEMPERATURE,NULL);
		}
	}	
}	
